package com.zhihuishu.micro.course.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.zhihuishu.micro.course.dao.TagMapper;
import com.zhihuishu.micro.course.dto.CourseTagDto;
import com.zhihuishu.micro.course.model.CourseTag;
import com.zhihuishu.micro.course.model.Tag;
import com.zhihuishu.micro.course.service.TagService;
import com.zhihuishu.toolkit.helper.BeanHelper;

@Service("tagService")
public class TagServiceImpl extends BaseService implements TagService {
	
	@Resource
	private TagMapper tagMapper ;

	@Override
	public List<CourseTagDto> listByCourseId(long courseId) {
		List<CourseTag> list = tagMapper.listByCourseId(courseId) ;
		return BeanHelper.transTo(list, CourseTagDto.class);
	}

	@Override
	public List<CourseTagDto> saveCourseTag(long courseId ,String ... tags) {
		Assert.notEmpty(tags ,"要创建的课程标签参数为空!");
		List<CourseTagDto> list = new ArrayList<CourseTagDto>() ;
		int [] tagIds = new int [tags.length] ;
		int index = 0 ;
		for(String content : tags) {
			Assert.notNull(content ,"标签正文为空!");
			// 检查标签是否已存在
			Integer tagId = tagMapper.getTagId(content) ;
			// 标签不存在，创建之
			if(tagId == null) {
				Tag tag = new Tag() ;
				tag.setContent(content);
				tagMapper.saveTag(tag);
				tagId = tag.getTagId() ;
			}
			if(tagId == null) throw new RuntimeException("创建课程标签出错!") ;
			tagIds[index ++] = tagId ;
			CourseTagDto ct = new CourseTagDto() ;
			ct.setCourseId(courseId);
			ct.setTagId(tagId);
			ct.setContent(content);
			list.add(ct) ;
		}
		// 批量创建课程标签
		tagMapper.saveCourseTag(courseId, tagIds);
		
		return list ;
	}

	@Override
	public void deleteCourseTag(long courseId ,int ... tagIds) {
		Assert.notNull(tagIds ,"要删除的课程标签ID参数为空!");
		tagMapper.deleteCourseTag(courseId, tagIds);
	}

}
